package com.ccnf.service.impl;

import com.ccnf.core.exception.BizException;
import com.ccnf.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

@Service
public class MailServiceImpl implements MailService {
    @Value("${spring.mail.username}")
    private String fromMail;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void exportAttachment(String subject, String toEmail, String bodyContent, String fileName, byte[] attachmentByteArray) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            mimeMessage.setFrom(fromMail);
            mimeMessage.setRecipients(Message.RecipientType.TO, toEmail);
            mimeMessage.setSubject(subject);

            MimeMultipart contentMultipart = new MimeMultipart("mixed");
            // 创建附件
            MimeBodyPart excelBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachmentByteArray, "application/octet-stream");
            DataHandler dataHandler = new DataHandler(dataSource);
            excelBodyPart.setFileName(fileName);
            excelBodyPart.setDataHandler(dataHandler);

            // 正文内容
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setText(bodyContent);

            contentMultipart.addBodyPart(excelBodyPart);
            contentMultipart.addBodyPart(textBodyPart);
            mimeMessage.setContent(contentMultipart);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BizException("邮件发送失败");
        }
    }
}
